<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * MY_Session Class extension for store userdata in database not in cookies
 */

/**
 * Session Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	MY_Sessions
 * @author		SeViR
 * @link		http://projects.sevir.org
 */

class MY_Session extends CI_Session{
	/**
	 * Session Constructor
	 *
	 * The constructor runs the session routines automatically
	 * whenever the class is instantiated.
	 */
	var $CI;
	var $table = 'ci_sessions';

	function MY_Session()
	{
		$this->CI = & get_instance(); 
		if (!($this->CI->db->table_exists($this->table))){
			$this->_create_sessions_table_sql();
		}
		parent::CI_Session();
	}


	//  ---------------------------------------------------------------------------

	/**
	 * Write the session cookie
	 *
	 * @access	public
	 * @return	void
	 */
	function _set_cookie($cookie_data = NULL)
	{
		if (is_null($cookie_data))
		{
			$cookie_data = $this->userdata;
		}

		// Serialize the userdata for the cookie
		$cookie_data = $this->_serialize($cookie_data);

		if ($this->sess_encrypt_cookie == TRUE)
		{
			$cookie_data = $this->CI->encrypt->encode($cookie_data);
		}
		else
		{
			// if encryption is not used, we provide an md5 hash to prevent userside tampering
			$cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
		}

		// Set the cookie
		setcookie(
					$this->sess_cookie_name,
					$cookie_data,
					($this->CI->config->item('sess_cookie_isnonpersistent'))?null:$this->sess_expiration + time(),
					$this->cookie_path,
					$this->cookie_domain,
					0
				);
	}

	//función nueva para recuperar los datos de una sesión ya logueada
	function getUserData($username){
		$result = $this->CI->db->query("select user_data from sessions where user_data LIKE '%:\"".$username."\";%' and last_activity = (SELECT MAX(last_activity) FROM sessions)");
		$result = $result->result_array();
		if (count($result) > 0){
			$this->set_userdata($this->_unserialize($result[0]["user_data"]));
		}
	}
	
	
	/**
	 * private function create campus table in the constructor library process
	 */
	function _create_sessions_table_sql(){
		$this->CI->load->dbforge();
		
		$this->CI->dbforge->add_field('session_id VARCHAR(40) DEFAULT \'0\' NOT NULL');

		$this->CI->dbforge->add_field('ip_address VARCHAR(16) DEFAULT \'0\' NOT NULL');
		$this->CI->dbforge->add_field('user_agent VARCHAR(50) NOT NULL');
		$this->CI->dbforge->add_field('last_activity INT(10) unsigned DEFAULT 0 NOT NULL');
		$this->CI->dbforge->add_field('user_data TEXT NOT NULL');

		$this->CI->dbforge->add_key('session_id', TRUE);
		if ($this->CI->dbforge->create_table($this->table, TRUE)) {	
			$r = $this->CI->db->query($this->CI->db->_list_tables());
		}else{
			log_message('debug', '# ci_sessions table creation error.');
		}
	}

}
// END Session Class
/* end of file */